<?php

require 'models/User.php';

class UserController extends BaseController {

    public function index() {

        if($this->isPostRequest()) {
            return $this->createUser();
        } else {
            return $this->listUsers();
        }
    }

    private function createUser() {

        $data = $_POST;

        $user = Model::factory('User')->create();

        $fields = array('email', 'fname', 'lname', 'address', 'zipcode', 'phoneno', 'password');

        $user->setFields($fields, $data);

        $errors = $user->validate();
        if(empty($errors)) {
            $user->save();
            $this->reportSuccess();
        } else {
            $this->reportErrors($errors);
        }

    }

    private function listUsers() {
        $users = Model::factory('User')->find_many();

        $ret = array();
        foreach ($users as $user) {
            $ret[] = $user->as_array();
        }

        return $ret;
    }

    public function authenticate() {
        $data = $_POST;
        $email = $data['email'];
        $password = $data['password'];

        $user = User::orm()->where('email', $email)->where('password', $password)->find_one();
        $result = false;
        if($user != null) {
            $this->reportSuccess();
        } else {
            $this->reportErrors(array('No such user'));
        }
    }

    public function getUser($email) {
        $user = User::orm()->find_one($email);
        
        if($user) {
            return $user->as_array();
        } else {
            $this->reportErrors('no such user');
        }
        
    }

}
